package com.warrior.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.warrior.Exception.ProjectException;
import com.warrior.entity.AdminUser;
import com.warrior.service.AdminService;
import com.warrior.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

/**
 *
 * Created by shawn on 2017/4/25.
 */
@Controller
public class AdminLoginController {


    @Autowired
    private AdminService adminService;


    /**
     * 用户登录路由
     * @param request req
     * @param response resp
     * @return ModelAndView
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public ModelAndView adminLogin(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new CModelAndView("/admin/admin_login",request,response);
        return mv;
    }


    /**
     * 用户登录
     * @param userName 用户名
     * @param password 密码
     * @param verifyCode 验证码
     * @param request req
     * @return json
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public String adminLogin(String userName,String password,String verifyCode,HttpServletRequest request){
        String returnData = null;
        String verify_code = (String) request.getSession().getAttribute("verifyCode");
        if (verify_code != null && !"".equals(verify_code)) {
            try {
                if (verify_code.equalsIgnoreCase(verifyCode)) {
                    //验证码通过验证用户名密码
                    String newPassword = MD5Util.getMD5(password);
                    boolean userLogin = this.adminService.validateAdminLogin(userName, newPassword);
                    if (userLogin) {
                        AdminUser user = this.adminService.findAdminUserByName(userName);
                        //写入用户登陆时间
                        DateUtil dateUtil = new DateUtil();
                        user.setLastLoginTime(dateUtil.Date2Timestamp(new Date()));
                        this.adminService.saveAdminUser(user);
                        //用户登陆成功后将用户名和id写入session
                        request.getSession().setAttribute("userId", user.getId());
                        request.getSession().setAttribute("userName", user.getUserName());
                        request.getSession().setAttribute("user", user);
                        returnData = ServerResponse.okToJsonString("success");
                    } else {
                        returnData = ServerResponse.okToJsonString("用户名或密码错误");
                    }
                } else {
                    returnData = ServerResponse.okToJsonString("验证码错误");
                }
            } catch (ProjectException | JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return returnData;
    }




    /**
     * generateImgVerfiy
     *
     * @param name 图片名
     * @param w    宽
     * @param h    高
     */
    @RequestMapping(value = "/verifyPic", method = RequestMethod.GET)
    public void generateImgVerify(String name, String w, String h, HttpServletRequest request,
                                  HttpServletResponse response) throws IOException {

        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        int width = 100;
        int height = 38;
        if (!"".equals(w) && null != w) {
            width = Integer.parseInt(w);
        }
        if (!"".equals(h) && null != h) {
            height = Integer.parseInt(h);
        }

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        VerifyCodeGenerateUtil verifyCodeGenerateUtil = new VerifyCodeGenerateUtil();

        Graphics generatePicCode = verifyCodeGenerateUtil.generatePicCode(image);

        // 生成随机类
        Random random = new Random();
        // 取随机产生的认证码(5位数字)
        StringBuilder bld = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            String rand = GenerateCodeUtil.randomInt(1);
            bld.append(rand);
            // 将认证码显示到图象中
            generatePicCode
                    .setColor(new Color(10 + random.nextInt(110), 10 + random.nextInt(110), 10 + random.nextInt(110)));// 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
            generatePicCode.drawString(rand, 12 * i + 10, 24);
        }
        String sRand = bld.toString();
        HttpSession session = request.getSession();
        // 将认证码存入SESSION
        if ("".equals(name) || null == name) {
            session.setAttribute("verifyCode", sRand);
        } else {
            session.setAttribute(name, sRand);
        }

        // 图象生效
        generatePicCode.dispose();
        ServletOutputStream responseOutputStream = response.getOutputStream();
        // 输出图象到页面
        ImageIO.write(image, "JPEG", responseOutputStream);

        // 以下关闭输入流！
        responseOutputStream.flush();
        responseOutputStream.close();

    }


    @RequestMapping("/500.htm")
    public ModelAndView errorPage(HttpServletResponse response, HttpServletRequest request){
        ModelAndView mv = new CModelAndView("500",request,response);
        return mv;
    }


}
